package model.p3_fitnessapp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * 
 * @author mauricegregor
 * 
 */
public class MySQLiteHelper extends SQLiteOpenHelper {

	/*
	 * ==========================================================================
	 * Globale Variablen
	 * ========================================================
	 */

	private SQLiteDatabase _myDataBase;
	private Context _myContext;
	private static String _PACKAGE_NAME;

	// The Android's default system path of your application database.
	private static String DB_PATH;
	private static final String DATABASE_NAME = "131121DBFitness.sqlite";
	private static final int DATABASE_VERSION = 1;

	/*
	 * ==========================================================================
	 * Konstruktoren ========================================================
	 */

	public MySQLiteHelper(Context context) {
		// super(context, DATABASE_NAME, null, DATABASE_VERSION);
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this._myContext = context;
		_PACKAGE_NAME = context.getPackageName();
	}

	public MySQLiteHelper(Context context, String DB_PATH) {
		// super(context, DATABASE_NAME, null, DATABASE_VERSION);
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this._myContext = context;
		this.DB_PATH = DB_PATH;
		System.out
				.println("Kontruktor MySQLiteHelper: DB_PATH " + this.DB_PATH);
	}

	/**
	 * Check if the database already exist to avoid re-copying the file each
	 * time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {

		Log.e(null, "CheckDatabase entered");
		SQLiteDatabase checkDB = null;

		try {
			String myPath = this.DB_PATH + DATABASE_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);
		} catch (SQLiteException e) {
			// database does't exist yet.
		}
		if (checkDB != null) {
			checkDB.close();
		}
		return checkDB != null ? true : false;
	}

	/**
	 * Creates a empty database on the system and rewrites it with your own
	 * database.
	 * */
	
	public void createDataBase() throws IOException {

		System.out.println("createDataBase entered!");
		boolean dbExist = checkDataBase();
//		 dbExist = false;

		if (dbExist) {

			Log.e(null, "Database already exists");

		} else {

			Log.e(null, "Database does not exist");

			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			this.getReadableDatabase();

			try {
				copyDataBase();
			} catch (IOException e) {
				throw new Error("Error copying database");
			}
		}
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {

		System.out.println("copyDataBase entered!");

		// Open your local db as the input stream
		InputStream myInput = _myContext.getAssets().open(DATABASE_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DATABASE_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	/**
	 * Not yet Implemented! Exports the Database from the App Installation path
	 * to an external Folder to test the functionality of certain DB
	 * manipulation methods.
	 * */
	private void exportDataBase() throws IOException {

		System.out.println("copyDataBase entered!");

		// Open your local db as the input stream
		InputStream myInput = _myContext.getAssets().open(DATABASE_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DATABASE_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	public void openDataBase() throws SQLException {

		System.out.println("openDataBase entered!");

		// Open the database
		String myPath = DB_PATH + DATABASE_NAME;
		System.out.println(myPath);
		_myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READONLY);
	}

	@Override
	public synchronized void close() {

		if (_myDataBase != null)
			_myDataBase.close();
		super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	public void deleteValue(/* Objekt objekt */) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.close();
	}

	/**
	 * Nimmt ein Exercise Objekt entgegen und schreibt die Daten des Objekts in
	 * die Notwendigen Tabellen. Notwenidge Tabellen sind: Exercise um die
	 * �bungsinhalte zu speichern EX_M um die Zugeh�rigkeit einer �bung zu einer
	 * Muskelgruppe fest zu halten
	 * 
	 * @param ex
	 *            Objekt des Typs Exercise
	 */

	public void addExercise(Exercise ex) {

		Log.i("MySQLitehelper.addExercise:", "METHOD ENTERED!");

		// Speichern der Parameter des Exercise Objekts
		String titel = ex.getTitel();
		String mugr = ex.getMusclegroup();
		int exID = -1;
		int mugrID = -1;

		Log.i("MySQLitehelper.addExercise:", "Titel: " + titel
				+ " Muskelgruppe: " + mugr);

		// Initialisierung eines beschreibbaren Datenbankobjekts
		SQLiteDatabase db = this.getWritableDatabase();
		Log.i("MySQLitehelper.addExercise:", "Database Connected!");

		// generieren eines INSERT Querys f�r das Exercise Objekt
		String insertQuery = "INSERT INTO exercise (name) VALUES ('" + titel
				+ "');";
		// Log.i("MySQLitehelper.addExercise:", "rawQuery insert Exercise! \n" +
		// insertQuery);

		// Query an Datenbank �bergeben
		db.execSQL(insertQuery);

		// Testausagbe aller eintr�ge im Ver�nderten Datatables
		// Generierung eines SQL Statements
		String selectIDquery = " SELECT * FROM exercise;";
		// Log.i("MySQLitehelper.addExercise:",
		// "rawQuery select ID of inserted Exercise! \n" + selectIDquery);
		Cursor cursor = db.rawQuery(selectIDquery, null);

		// Ausgabe des Ergebnisses der vorherigen Datenbankabfrage
		// System.out.println("Exercise Inhalt: ");
		// if (cursor.moveToFirst()) {
		// do {
		// System.out.println(cursor.getInt(cursor.getColumnIndex("_id")) + " "
		// + cursor.getString(cursor.getColumnIndex("name")));
		// } while (cursor.moveToNext());
		// }
		// System.out.println("Exercise Inhalte: EOF!");

		// cursor.close();

		// Anfrage an DB um ID der Muskelgruppe zu erhalten die in der �bung
		// verwendet wird
		String selectExIdQuery = "SELECT * FROM exercise WHERE name LIKE '"
				+ titel + "';";
		// Log.i("MySQLitehelper.addExercise:","rawQuery get ID of related Exercise! \n"
		// + selectExIdQuery);
		cursor = db.rawQuery(selectExIdQuery, null);

		cursor.moveToFirst();

		ex.setId(cursor.getInt((cursor.getColumnIndex("_id"))));
		exID = ex.getId();

		cursor.close();

		// Get ID of muscle_group
		String selectMuGrQuery = "SELECT * FROM muscle_group WHERE name LIKE '"
				+ mugr + "';";
		// Log.i("MySQLitehelper.addExercise:","rawQuery get ID of related MuscleGroup! \n"
		// + selectMuGrQuery);

		cursor = db.rawQuery(selectMuGrQuery, null);

		System.out.println(cursor.moveToFirst());

		MuscleGroup m_g = new MuscleGroup();
		m_g.setId(cursor.getInt(cursor.getColumnIndex("_id")));
		mugrID = m_g.getId();

		cursor.close();

		// Einf�gen der exID MuGrID in Hilfstabelle der Datenbank
		String addExToMuGrQuery = "INSERT INTO ex_m (id_muscle, id_exercise) "
				+ "VALUES ('" + mugrID + "', '" + exID + "');";
		// Log.i("MySQLitehelper.addExercise:",
		// "rawQuery insert MuscelGroupID and ExerciseID into Table ex_m! \n"
		// + addExToMuGrQuery);
		db.execSQL(addExToMuGrQuery);

		// Testausagbe aller eintr�ge im Ver�nderten Datatables
		// Generierung eines SQL Statements
		// String selectEX_Mquery = " SELECT * FROM ex_m;";
		// Log.i("MySQLitehelper.addExercise:",
		// "rawQuery select ALL from ex_m! \n" + selectEX_Mquery);
		// cursor = db.rawQuery(selectEX_Mquery, null);

		// Ausgabe des Ergebnisses der vorherigen Datenbankabfrage
		// System.out.println("EX_M Inhalt: ");
		// if (cursor.moveToFirst()) {
		// do {
		// System.out.println(cursor.getInt(cursor.getColumnIndex("_id")) + " "
		// + cursor.getString(cursor.getColumnIndex("id_muscle")) + " " +
		// cursor.getString(cursor.getColumnIndex("id_exercise")));
		// } while (cursor.moveToNext());
		// }
		// System.out.println("Exercise Inhalte: EOF!");

		cursor.close();

		db.close();

		Log.i("MySQLitehelper.addExercise:", "Database Closed!");

	}

	public Exercise getExerciseByID(int id) {
		Exercise ex = new Exercise();

		SQLiteDatabase db = this.getReadableDatabase();

		String getExByID = "SELECT * FROM exercise WHERE _id='" + id + "';";
		System.out.println(getExByID);

		Cursor cursor = db.rawQuery(getExByID, null);

		cursor.moveToFirst();

		ex.setId(cursor.getInt(cursor.getColumnIndex("_id")));
		ex.setTitel(cursor.getString(cursor.getColumnIndex("name")));

		System.out.println("getExerciseByID: ID: " + ex.getId() + " , Titel: "
				+ ex.getTitel());

		cursor.close();

		db.close();

		return ex;
	}

	/**
	 * Die Methode nimmt ein MuskelgruppenID entgegen und gibt eine Arrayliste
	 * von Exercise Objekten zur�ck. Diese enthalten jeweils die Informationen
	 * zu den zugeh�rigen Datenbankeintr�gen.
	 * 
	 * @param id_wp
	 * @return
	 */
	public ArrayList<Exercise> getExerciseByTrainingplanID(int id_wp) {

		System.out.println("getExerciseByTrainingsplan started!");

		Exercise ex = new Exercise();

		ArrayList<Exercise> a_tmp1 = new ArrayList<Exercise>();

		SQLiteDatabase db = this.getWritableDatabase();

		String selectExerciseID = "SELECT * FROM ex_wp WHERE id_wp='" + id_wp
				+ "';";
		System.out.println(selectExerciseID);

		Cursor cursor = db.rawQuery(selectExerciseID, null);

		// Erzeugt eine Arrayliste von Exercise Objekten deren IDs aus
		// der Hilfstabelle ex_wp entnommen werden k�nnen und zueinem bestimmten
		// Traininsplan geh�ren
		if (cursor.moveToFirst()) {
			do {
				Exercise ex_tmp = new Exercise();
				ex_tmp.setId(cursor.getInt(cursor.getColumnIndex("id_exercise")));

				a_tmp1.add(ex_tmp);
			} while (cursor.moveToNext());
		}
		cursor.close();

		for (Exercise tmp : a_tmp1) {
			System.out.println("Exercise ID: " + tmp.getId());
			String selectAllExByTrainPlanID = "SELECT * FROM exercise WHERE _id='"
					+ tmp.getId() + "';";

			cursor = db.rawQuery(selectAllExByTrainPlanID, null);
			cursor.moveToFirst();

			if (cursor.getCount() == 1) {
				System.out.println("Cursor.getCount = 1");
				System.out.println(cursor.getString(cursor
						.getColumnIndex("name")));
				tmp.setTitel(cursor.getString(cursor.getColumnIndex("name")));
			} else {
				System.out.println("Cursor.getCount not 1");
			}

			for (Exercise exer : a_tmp1) {
				System.out
						.println("Ausgabe aller gesammelter Exercise Objekte: ");
				System.out.println("TEST: Exercise ID = " + exer.getId()
						+ " , Exercise Name = " + exer.getTitel());
			}
		}

		db.close();

		return a_tmp1;
	}

	public ArrayList<Exercise> getExerciseByMusclegroupID(int mg_id) {

		SQLiteDatabase db = getReadableDatabase();

		System.out.println("getExerciseByTrainingsplan started!");

		ArrayList<Exercise> a_tmp1 = new ArrayList<Exercise>();

		String selectExerciseID = "SELECT * FROM ex_m WHERE id_muscle='"
				+ mg_id + "';";
		System.out.println(selectExerciseID);

		Cursor cursor = db.rawQuery(selectExerciseID, null);

		// Erzeugt eine Arrayliste von Exercise Objekten deren IDs aus
		// der Hilfstabelle ex_wp entnommen werden k�nnen und zueinem bestimmten
		// Traininsplan geh�ren
		if (cursor.moveToFirst()) {
			do {
				Exercise ex_tmp = new Exercise();
				ex_tmp.setId(cursor.getInt(cursor.getColumnIndex("id_exercise")));

				a_tmp1.add(ex_tmp);
			} while (cursor.moveToNext());
		}
		cursor.close();

		for (Exercise tmp : a_tmp1) {
			System.out.println("Exercise ID: " + tmp.getId());
			String selectAllExByTrainPlanID = "SELECT * FROM exercise WHERE _id='"
					+ tmp.getId() + "';";

			cursor = db.rawQuery(selectAllExByTrainPlanID, null);
			cursor.moveToFirst();

			if (cursor.getCount() == 1) {
				System.out.println("Cursor.getCount = 1");
				System.out.println(cursor.getString(cursor
						.getColumnIndex("name")));
				tmp.setTitel(cursor.getString(cursor.getColumnIndex("name")));
			} else {
				System.out.println("Cursor.getCount not 1");
			}

		}

		for (Exercise exer : a_tmp1) {
			System.out.println("Ausgabe aller gesammelter Exercise Objekte: ");
			System.out.println("TEST: Exercise ID = " + exer.getId()
					+ " , Exercise Name = " + exer.getTitel());
		}

		db.close();

		return a_tmp1;

	}

	public ArrayList<Exercise> getExerciseByMuscleGroupIDandTrainingplanID(
			int mg_id, int tp_id) {
		ArrayList<Exercise> a_ex = new ArrayList<Exercise>();

		SQLiteDatabase db = this.getReadableDatabase();

		/* ... */

		String getExByMG = "SELECT * FROM ex_wp WHERE id_wp='" + tp_id + "';";

		Cursor cursor = db.rawQuery(getExByMG, null);

		if (cursor.moveToFirst()) {
			do {
				Exercise ex_tmp = new Exercise();
				ex_tmp.setId(cursor.getInt(cursor.getColumnIndex("id_exercise")));

				a_ex.add(ex_tmp);
			} while (cursor.moveToNext());
		}
		cursor.close();

		ArrayList<Exercise> a_del = new ArrayList<Exercise>();

		for (Exercise ex : a_ex) {
			String selectMG = "SELECT * FROM ex_m WHERE id_exercise='"
					+ ex.getId() + "';";

			cursor = db.rawQuery(selectMG, null);

			cursor.moveToFirst();
			System.out.println(cursor.getCount());

			if (cursor.getInt(cursor.getColumnIndex("id_muscle")) == mg_id) {
				System.out.println("MuscleGroup ID vorhanden!");
			} else {
				System.out.println("MuscleGroup ID mismatch!");
				a_del.add(ex);
			}
		}

		for (Exercise ex : a_del) {
			System.out.println("Remove Item from Arraylist!");
			a_ex.remove(ex);
		}

		for (Exercise ex : a_ex) {
			String getExName = "SELECT * FROM exercise WHERE _id='"
					+ ex.getId() + "';";
			System.out.println(getExName);
			cursor = db.rawQuery(getExName, null);
			System.out.println(cursor.getCount());
			String[] str = cursor.getColumnNames();

			for (int i = 0; i < str.length; i++) {
				System.out.println(str[i]);
			}

			cursor.moveToFirst();
			ex.setTitel(cursor.getString(cursor.getColumnIndex("name")));

		}

		for (Exercise ex : a_ex) {
			System.out.println("Ausgabe aller gesammelter Exercise Objekte: ");
			System.out.println("TEST: Exercise ID = " + ex.getId()
					+ " , Exercise Name = " + ex.getTitel());
		}

		db.close();

		return a_ex;
	}

	// Trainingsplaene

	public void addTrainingplanWithExercises(TrainingPlan tp,
			ArrayList<Exercise> a_ex) {

		Log.i("MySQLiteHelper.addTrainingplanWithExercise", "Method entered!");

		SQLiteDatabase db = this.getWritableDatabase();

		String setTrainingsplan = "INSERT INTO workout_plan ( name ) VALUES ('"
				+ tp.getName() + "');";

		Log.i("MySQLiteHelper.addTrainingplanWithExercise",
				"SQL Statement will be executed! \n" + setTrainingsplan);

		db.execSQL(setTrainingsplan);

		String getTrainingplanIDbyTrainingplanName = "SELECT * FROM workout_plan WHERE name='"
				+ tp.getName() + "';";

		Log.i("MySQLiteHelper.addTrainingplanWithExercise",
				"SQL Statement will be executed! \n"
						+ getTrainingplanIDbyTrainingplanName);

		Cursor cursor = db.rawQuery(getTrainingplanIDbyTrainingplanName, null);

		cursor.moveToFirst();

		System.out.println("TEST: Trainingplan: "
				+ cursor.getInt(cursor.getColumnIndex("_id")));
		int wpID = cursor.getInt(cursor.getColumnIndex("_id"));

		for (Exercise ex : a_ex) {
			String insertInEx_WP = "INSERT INTO ex_wp (id_wp, id_exercise) "
					+ "VALUES ('" + wpID + "', '" + ex.getId() + "');";
			System.out.println(insertInEx_WP);
			db.execSQL(insertInEx_WP);
		}

		// Ausgabe der Ver�nderten Tabelleninhalte
		String getAllEX_WP = "SELECT * FROM ex_wp;";
		cursor = db.rawQuery(getAllEX_WP, null);

		System.out.println("EX_WP Inhalt: ");
		if (cursor.moveToFirst()) {
			do {
				System.out
						.println(cursor.getInt(cursor.getColumnIndex("_id"))
								+ " "
								+ cursor.getString(cursor
										.getColumnIndex("id_wp"))
								+ " "
								+ cursor.getString(cursor
										.getColumnIndex("id_exercise")));
			} while (cursor.moveToNext());
		}
		System.out.println("EX_WP Inhalte: EOF!");

		cursor.close();
		db.close();
	}

	public ArrayList<TrainingPlan> getAllTrainingplans() {
		ArrayList<TrainingPlan> a_tp = new ArrayList<TrainingPlan>();

		SQLiteDatabase db = this.getReadableDatabase();

		String selectAlltrainingplans = "SELECT * FROM workout_plan;";

		Cursor cursor = db.rawQuery(selectAlltrainingplans, null);

		if (cursor.moveToFirst()) {
			do {
				TrainingPlan tp = new TrainingPlan();
				tp.setId(cursor.getInt(cursor.getColumnIndex("_id")));
				tp.setName(cursor.getString(cursor.getColumnIndex("name")));
				a_tp.add(tp);
			} while (cursor.moveToNext());
		}
		cursor.close();

		for (TrainingPlan tp : a_tp) {
			System.out.println("Trainingsplan Object Data: ID =" + tp.getId()
					+ " Name = " + tp.getName());
		}

		db.close();

		return a_tp;
	}

	// Muskelgruppen

	public ArrayList<MuscleGroup> getAllMusclegroups() {
		ArrayList<MuscleGroup> a_mg = new ArrayList<MuscleGroup>();

		SQLiteDatabase db = this.getReadableDatabase();

		String selectQuery = " SELECT * FROM muscle_group;";

		Cursor cursor = db.rawQuery(selectQuery, null);

		if (cursor.moveToFirst()) {
			do {
				MuscleGroup m_g = new MuscleGroup();
				m_g.setId(cursor.getInt(cursor.getColumnIndex("_id")));
				m_g.setName(cursor.getString(cursor.getColumnIndex("name")));
				a_mg.add(m_g);
			} while (cursor.moveToNext());
		}
		cursor.close();

		// TEST Ausgabe des Arrays
		for (MuscleGroup m_g : a_mg) {
			System.out.println("Muscle_Group Object Data: ID =" + m_g.getId()
					+ " Name = " + m_g.getName());
		}

		db.close();

		return a_mg;
	}

	public ArrayList<MuscleGroup> getMuscleGroupByExerciseID(int ex_id) {
		ArrayList<MuscleGroup> a_mg = new ArrayList<MuscleGroup>();

		SQLiteDatabase db = this.getReadableDatabase();

		String getMgByEx = "SELECT * FROM ex_m WHERE id_exercise='" + ex_id
				+ "';";

		Log.i("MySQLiteHelper.getMusclegroupByExerciseID",
				"Zugriff auf ex_m fuer Muskelgruppen ID! \n" + getMgByEx);
		Cursor cursor = db.rawQuery(getMgByEx, null);

		if (cursor.moveToFirst()) {
			do {
				MuscleGroup m_g = new MuscleGroup();
				m_g.setId(cursor.getInt(cursor.getColumnIndex("id_muscle")));

				a_mg.add(m_g);
			} while (cursor.moveToNext());
		}
		cursor.close();

		for (MuscleGroup mg : a_mg) {
			String getMuscleName = "SELECT * FROM muscle_group WHERE _id='"
					+ mg.getId() + "';";
			cursor = db.rawQuery(getMuscleName, null);
			cursor.moveToFirst();
			mg.setName(cursor.getString(cursor.getColumnIndex("name")));
		}

		// TEST Ausgabe des Arrays
		for (MuscleGroup m_g : a_mg) {
			System.out.println("Muscle_Group Object Data: ID =" + m_g.getId()
					+ " Name = " + m_g.getName());
		}

		cursor.close();

		db.close();

		return a_mg;
	}

	public ArrayList<MuscleGroup> getMuscleGroupByTrainingplanID(int tp_id) {

		ArrayList<MuscleGroup> a_mg = new ArrayList<MuscleGroup>();

		SQLiteDatabase db = getReadableDatabase();

		ArrayList<Exercise> a_ex = getExerciseByTrainingplanID(tp_id);

		for (Exercise ex : a_ex) {

			ArrayList<MuscleGroup> temp = getMuscleGroupByExerciseID(ex.getId());

			for (MuscleGroup muscleGroup : temp) {
				Log.i("MySQLiteHelper.getMusclegroupByTrainingplanID",
						"ID: " + muscleGroup.getId() + " Name: "
								+ muscleGroup.getName());
			}

			for (MuscleGroup mg : temp) {

				int mg_id = mg.getId();
				boolean exists = false;

				for (MuscleGroup mg1 : a_mg) {

					if (mg1.getId() == mg_id) {
						exists = true;
					}
				}
				System.out.println(exists);

				if (exists == false) {
					a_mg.add(mg);
				}
			}
		}

		db.close();

		System.out.println("FINAL Arraycontent! ");
		for (MuscleGroup mg2 : a_mg) {
			System.out
					.println("ID: " + mg2.getId() + " Name: " + mg2.getName());
		}

		return a_mg;
	}

	// Historie
	/**
	 * Die Methode gibt alle in der Datenbank vorhanden Eintr�ge der Tabelle
	 * History als Arrayliste von History Objekten zur�ck.
	 * 
	 * @return
	 */
	public ArrayList<History> getAllHistorys() {
		ArrayList<History> a_hi = new ArrayList<History>();

		SQLiteDatabase db = this.getReadableDatabase();

		String getAllHistorys = "SELECT * FROM history;";

		System.out.println(getAllHistorys);

		Cursor cursor = db.rawQuery(getAllHistorys, null);

		if (cursor.moveToFirst()) {
			do {
				History h = new History();
				h.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
				h.setDate(cursor.getString(cursor.getColumnIndex("date")));
				h.setId_exercise(cursor.getInt(cursor
						.getColumnIndex("id_exercise")));
				h.setName_exercise(getExerciseByID(h.getId_exercise())
						.getTitel());
				h.setSet(cursor.getInt(cursor.getColumnIndex("set_nr")));
				h.setKilograms(cursor.getInt(cursor.getColumnIndex("kg")));
				h.setRepetition(cursor.getInt(cursor
						.getColumnIndex("repetition")));
				a_hi.add(h);
			} while (cursor.moveToNext());
		}

		cursor.close();

		int i = 0;
		for (History h : a_hi) {
			System.out.println("History " + i + " : " + "ID: " + h.get_id()
					+ " Datum: " + h.getDate() + " �bung: "
					+ h.getId_exercise() + " �bung Titel: "
					+ h.getName_exercise() + " SatzNr: " + h.getSet() + " Kg: "
					+ h.getKilograms() + " Wiederholungen: "
					+ h.getRepetition());
			i++;
		}

		db.close();

		return a_hi;

	}

	/**
	 * Die Methode nimmt ein Objekt vom Typ History entgegen und speicher den
	 * Inhalt in der Datenbank.
	 * 
	 * @param history
	 */
	public void addHistory(History history) {

		System.out.println("addHistory method entered!");

		SQLiteDatabase db = this.getWritableDatabase();
		Timemanager time = new Timemanager();
		String str = history.getDate().toString();

		String addHistory = "INSERT INTO history (date, id_exercise, set_nr, kg, repetition)"
				+ " VALUES ('"
				+ str
				+ "','"
				+ history.getId_exercise()
				+ "','"
				+ history.getSet()
				+ "','"
				+ history.getRepetition()
				+ "','"
				+ history.getKilograms() + "');";

		System.out.println(addHistory);

		db.execSQL(addHistory);

		System.out.println("TEST!");

		// ArrayList<History> h_temp = getAllHistorys();

		db.close();

	}

	// Einstellungen

}
